package com.jp.knowledge.logic;

import android.content.Context;

import com.jiayen.util.ToasUtil;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.util.SignVerifyUtil;
import com.jp.knowledge.util.TimeUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by jiayen on 17/6/8.
 */

public class DownloadLogic {

    private Context  mContext;
    private boolean showTasot;
    private DownloadCallback  downloadCallback;
    public DownloadLogic(Context  mContext,boolean showTasot){
        this.mContext=mContext;
        this.showTasot=showTasot;
    }

    public void setDownloadCallback(DownloadCallback downloadCallback) {
        this.downloadCallback = downloadCallback;
    }

    public void download(String url, final String path){

        HttpHelper.getInstance(mContext).downloadFile(url, new Func1<ResponseBody, String>() {
            @Override
            public String call(ResponseBody body) {
                String filePath =  save(body,path);//保存pdf文件
                return filePath;
            }
        }, new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String path) {
                if(showTasot)
                ToasUtil.toast(mContext,"已保存在"+path);
                if(downloadCallback!=null)
                    downloadCallback.success(path);
            }
        });
    }

    private String save(ResponseBody body,String path) {
//        String path =  mContext.getCacheDir().getPath()+"/img/"+ TimeUtil.formatYearData(System.currentTimeMillis())+"/"+ SignVerifyUtil.encrypt(list.get(viewPager.getCurrentItem()))+".jpg";
        File file = new File(path);
        File parent = file.getParentFile();
        if (!parent.exists()){
            parent.mkdirs();
        }
        InputStream input = body.byteStream();
        try {
            OutputStream out = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len=input.read(buf))!=-1){
                out.write(buf,0,len);
            }
            out.close();
            input.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    public interface  DownloadCallback{
        void  success(String path);
    }
}
